package com.example.demo.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.domain.Girl;
import com.example.demo.domain.Result;
import com.example.demo.properties.GirlInterface;
import com.example.demo.service.GirlService;
import com.example.demo.util.ResultUtil;


@RestController
public class GirlContorller {
	
	@Autowired
	private GirlInterface girlInterface;
	
	@Autowired
	private GirlService girlService;
	
	/*
	 * 查询女生列表
	 * @return
	 */
	@GetMapping(value = "/girls")
	public List<Girl> girlList(){
		
		return girlInterface.findAll();
				
	}
	/*
	 * 添加一个女生
	 */
	@PostMapping(value ="/girls")
	public Result<Girl> girlAdd(@Valid Girl girl,BindingResult bindingResult) {
		
		if(bindingResult.hasErrors()) {
			return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
			
		}
		
		girl.setAge(girl.getAge());
		
		girl.setSize(girl.getSize());
		
		return ResultUtil.success(girlInterface.save(girl));
	}
	
	/*
	 * 查询一个女生
	 */
	@GetMapping(value = "/girls/{id}")
	public Girl getOneGirl(@PathVariable("id") Integer id) {
		
		return girlInterface.findOne(id);
		
	}
	/*
	 * 更新
	 */
	@PutMapping(value ="/girls/{id}")
	public Girl girlUpdata(@PathVariable("id") Integer id,
			@RequestParam("size") String size,
			@RequestParam("age") Integer age) {
		
		Girl girl = new Girl();
		
		girl.setId(id);
		girl.setAge(age);
		girl.setSize(size);
		
		return girlInterface.save(girl);
	}
	/*
	 * 删除
	 */
	@DeleteMapping(value = "/girls/delete/{id}")
	public void deleteGirl(@PathVariable("id") Integer id) {
		
		girlInterface.delete(id);
		
	}
	/*
	 * 通过年龄查询女生列表
	 */
	@GetMapping(value ="/girls/age/{age}")
	public List<Girl> GirlListByAge(@PathVariable("age") Integer age){
		
		return girlInterface.findByAge(age);
		
	}
	
	@PostMapping(value = "/girls/two")
	public void girlTwo() {
	
		girlService.insertTwo();
	}
	@GetMapping(value ="/girls/getAge/{id}")
	public void getAge(@PathVariable("id") Integer id) throws Exception{
		
		girlService.getAge(id);
		
	}
}
